<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '实验记录列表',
    enablePullDownRefresh: true,
  },
}
</route>
<template>
  <page-meta :root-font-size="setting.rootFontSize"
    :page-style="`overflow:${selectSchemeShow ? 'hidden' : 'visible'};`"></page-meta>
  <view style="
      min-height: calc(100vh - 350rpx);
      padding: 0 20rpx;
      padding-top: 350rpx;
      background-color: #f2f2f1;
    ">
    <view class="tabbar">
      <wd-navbar style="min-height: 100rpx" title="实验记录" :bordered="false" safeAreaInsetTop>
        <template #left>
          <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
        </template>
      </wd-navbar>
      <view class="cu-bar search-container">
        <view class="search-form round">
          <wd-input type="text" prop="invName" v-model="search" no-border clearable placeholder="请输入"
            style="display: flex; align-items: center; width: 100%; height: 100%; padding: 0 20rpx"
            @confirm="handleSearch" confirm-type="search" />
          <text class="filter-icon cuIcon-searchlist" @click="filterIsShow = true"></text>
        </view>
        <view class="action">
          <button @click="handleSearch()" class="cu-btn bg-gradual-green shadow-blur round" style="margin-right: 10rpx">
            查询
          </button>
          <button @click="handleAdd()" class="cu-btn bg-gradual-blue shadow-blur round"
            v-if="checkPremiss('experiment_experimentRecord_add')">
            新增
          </button>
        </view>
      </view>
      <view class="tabs">
        <view v-for="(item, index) in tableList" :class="['item', 'i' + index, item.value === activeTab ? 'on' : '']"
          :key="item.value" @click="onTabChange(item.value)">
          {{ item.label }}
        </view>
      </view>
    </view>
    <template v-for="item in dataList" :key="item.id">
      <card :_D="item" :isOpt="true" @refresh="refresh"></card>
    </template>
    <wd-loadmore :state="loadMore" finishedText="没有更多了" @reload="handleSearch()"></wd-loadmore>
    <wd-popup v-model="filterIsShow" position="bottom" :close-on-click-modal="false"
      custom-style="padding: 32rpx;border-top-left-radius:60rpx;border-top-right-radius:60rpx;" @close="handleClose">
      <view class="cu-dialog" @click.stop="">
        <view class="cu-bar bg-white">
          <view class="action"></view>
          <view class="action mks" @click="filterIsShow = false">取消</view>
          <!-- <view class="action text-blue mks" @tap="handleSearch()">确定</view> -->
        </view>
        <view class="filter_container">
          <view class="block">
            <view class="label">方案编号</view>
            <view class="row">
              <wd-input type="text" v-model="state.webSQLList.schemeNo" clearable placeholder="请输方案编号"
                style="width: 100%" />
            </view>
          </view>
          <view class="block">
            <view class="label">记录编号</view>
            <view class="row">
              <wd-input type="text" v-model="state.webSQLList.recordNo" clearable placeholder="请输入记录编号"
                style="width: 100%" />
            </view>
          </view>
          <view class="block">
            <view class="label">开始日期</view>
            <view class="row">
              <wd-datetime-picker v-model="state.startTime" type="date" :default-value="defaultValue" style="flex: 1" />
              <!-- <uni-datetime-picker type="date" return-type="string" v-model="state.startTime"
								placeholder="开始日期" /> -->
            </view>
          </view>
          <view class="block">
            <view class="label">结束日期</view>
            <view class="row">
              <wd-datetime-picker v-model="state.endTime" type="date" :default-value="defaultValue" style="flex: 1" />
              <!-- <uni-datetime-picker type="date" return-type="string" v-model="state.endTime"
								placeholder="结束日期" /> -->
            </view>
          </view>
          <view class="block">
            <view class="row">
              <view class="btn" @click="resetFilter">重置</view>
              <view class="btn primary" @click="handleSearch()">确认</view>
            </view>
          </view>
        </view>
      </view>
    </wd-popup>

    <selectScheme :show="selectSchemeShow" @checkLeaguer="toFrom" @hideModal="selectSchemeShow = false" />
  </view>
</template>

<script lang="ts" setup name="sign">
import { useSetting } from '@/stores/setting';
import { fetchList } from '@/service/pm-record';
import { useDict } from '@/hooks/dict';
import { formatByDayjs } from '@/utils/util';
import { nextTick } from 'process';
import { request } from '@/utils/request';
import { useUserStore } from '@/stores/user';
import selectScheme from '../components/selectScheme.vue';
import card from './component/card.vue';
import showModal from '@/utils/modal'

const dataList = ref([]);
const setting = useSetting();
const { bill_status } = useDict('bill_status');
const loadMore = ref<any>('finished');

const page = ref(1);
const loading = ref(false);
const userStore: any = useUserStore();

const defaultValue = ref<number>(Date.now());

const search = ref("")
const state = reactive({
  webSQLList: {
    status: null,
    recordNo: null,
    schemeNo: null,
  },

  webSql: null,
  startTime: '',
  endTime: '',
  size: 20,
  orders: [
    {
      column: 'scheme_id',
      asc: false,
    },
    {
      column: 'sn',
      asc: true,
    },
  ],
});

const selectSchemeShow = ref(false);

const checkPremiss = (k) => {
  return userStore.userInfos.authBtnList.some((v: string) => v === k);
};

const getData = () => {
  uni.showLoading();
  loading.value = true;
  loadMore.value = 'loading';

  if (state.webSql === null) state.webSql = '';

  const a = encodeURIComponent(state.webSql);
  const searchStr = encodeURIComponent(search.value);
  request({
    url: `/pm/experimentRecord/page?webSql=${a}&current=${page.value}&size=${state.size}&search=${searchStr}`,
    method: 'POST',
    data: state,
  })
    .then((res) => {
      if (res.code !== 0) {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
        return;
      }
      dataList.value = dataList.value.concat(res.data.records);
      if (res.data.records.length === state.size) {
        loadMore.value = 'loadEnd';
      } else {
        loadMore.value = 'finished';
      }
    })
    .catch((err) => {
      loadMore.value = 'finished';
      uni.showToast({
        title: err.data?.msg || err.msg,
        icon: 'none',
      });
    })
    .finally(() => {
      uni.hideLoading();
      loading.value = false;
      uni.stopPullDownRefresh();
    });
};

const goBack = () => {
  uni.navigateBack();
};

watch(
  () => bill_status.value,
  (n) => {
    console.log('=----b', n);
    nextTick(() => {
      tableList.value = [
        {
          label: '全部',
          value: null,
          color: '#108ee9',
        },
        ...n,
      ];
    });
  },
  {
    deep: true,
    immediate: true,
  },
);

onLoad(() => {
  getData();
});

const filterIsShow = ref(false);

const handleSearch = (e?) => {
  // if (e !== undefined) {
  //   state.webSQLList.schemeNo = e;
  // }
  let startDate = state.startTime;
  let endDate = state.endTime;
  if (endDate && new Date(startDate).getTime() > new Date(endDate).getTime()) {
    uni.showToast({
      title: '开始时间不能大于结束时间',
      icon: 'none',
      mask: true,
    });
    return;
  }
  const so = fromToWebSqlMap();
  if (state.endTime || state.startTime) {
    startDate = state.startTime ? formatByDayjs(state.startTime, 'YYYY-MM-DD 00:00:00') : '';
    endDate = state.endTime ? formatByDayjs(state.endTime, 'YYYY-MM-DD 23:59:59') : '';
    state.webSql = `create_time between '${startDate}' and '${endDate}'`;
  } else {
    state.webSql = so && so.length ? so.join(' and ') : null;
  }
  dataList.value = [];
  page.value = 1;

  getData();
  filterIsShow.value = false;
};

const fromToWebSqlMap = () => {
  const list = [];
  Object.entries(state.webSQLList).map((item) => {
    if (item[1]) {
      item[0] = item[0].replace(/([A-Z])/g, '_$1').toLowerCase();
      list.push(`${item[0]} like '%${item[1]}%'`);
    }
  });
  return list;
};

function queryRecordStatusBySchemeId(schemeId?: string) {
  return request({
    url: '/pm/experimentScheme/queryRecordStatusBySchemeId/' + schemeId,
    method: 'get',
  });
}


const queryRecordStatus = async (row) => {
  try {
    const res = await queryRecordStatusBySchemeId(row.id)
    if (res.code === 0) {
      return false
    } else {
      return res.msg
    }

  } catch (error) {
    return error.msg
  }
}


const toFrom = async (payload) => {
  const res = await queryRecordStatus(payload);
  if (res) {
    showModal({
      title: '提示',
      content: `${res}\n(具体请在电脑端点击关联查询查看)`,
      cancelColor: '#333333',
      confirmColor: '#2d84fb',
      cancelText: '否',
      confirmText: '是',
      confirm: () => {
        console.log('取消')
      },
      cancel: () => {
        uni.navigateTo({
          url: `/pages/pm/experiment/record/form?schemeId=${payload.id}`,
        });

      }
    })
  } else {
    uni.navigateTo({
      url: `/pages/pm/experiment/record/form?schemeId=${payload.id}`,
    });
  }

};

const handleAdd = () => {
  selectSchemeShow.value = true;
};

const activeTab = ref(null);

const tableList = ref([
  {
    text: '全部',
    value: null,
    color: '#108ee9',
  },
  {
    label: '开立',
    value: '0',
    color: '#108ee9',
  },
  {
    label: '审核中',
    value: '1',
    color: '#d46b08',
  },
  {
    label: '通过',
    value: '2',
    color: '#87d068',
  },
  {
    label: '拒绝',
    value: '3',
    color: '#f50',
  },
  // {
  //   text: '撤回',
  //   value: '9',
  //   color: '#f50',
  // },
]);
const onTabChange = (e) => {
  activeTab.value = e;
  state.webSQLList.status = e;
  dataList.value = [];
  page.value = 1;
  handleSearch();
  // resetFilter();
};

onPullDownRefresh(() => {
  // 重新获取
  refresh();
});
onReachBottom(() => {
  if (loading.value) return;
  if (loadMore.value === 'loadEnd') {
    page.value++;
    getData();
  }
});

const refresh = () => {
  dataList.value = [];
  page.value = 1;
  getData();
};

uni.$on('refresh', () => {
  refresh();
});

const handleClose = () => {
  filterIsShow.value = false;
};

const resetFilter = () => {
  handleClose();
  state.webSQLList.recordNo = null;
  state.webSQLList.schemeNo = null;
  state.startTime = null;
  state.endTime = null;
  handleSearch();
};
</script>

<style lang="scss" scoped>
$padding: 30rpx;

.canvas-box {
  .canvas {
    height: 300rpx;
    transition: height 0.3s;
  }

  .btns {
    margin-top: 10rpx;
    transition: transform 0.3s;

    .btn {
      width: auto;
      height: 50rpx;
    }
  }
}

.full-screen {
  flex-direction: row;
  height: calc(100vh - 88rpx);

  .canvas {
    width: calc(100% - 100rpx);
    height: 100%;
    margin-left: 100rpx;
  }

  .btns {
    position: absolute;
    align-items: center;
    width: calc(100vh - (88rpx + $padding * 2));
    height: 100rpx;
    transform: translate(100rpx, 0) rotate(90deg);
    transform-origin: top left;

    .btn-box {
      flex-direction: row;
    }
  }
}

.tabbar {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  background: linear-gradient(45deg, #0081ff, #1ab3f5);
}

.tabbar_c {
  height: 100%;
  font-weight: 800;
  color: white;
  letter-spacing: 2px;
  background: linear-gradient(45deg, #0081ff, #1ab3f5);
}

.bolck {
  background: linear-gradient(45deg, #0081ff, #1ab3f5);
}

.task_list {
  background: #f7f7f7;
}

.cu-bar {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 50px;
}

.cu-bar .search-form {
  display: flex;
  flex: 1;
  align-items: center;
  height: 64rpx;
  margin: 0 30rpx;
  overflow: hidden;
  /* padding: 0 40rpx; */
  font-size: 24rpx;
  line-height: 64rpx;
  color: #333;
  background-color: white;
}

.search-container .filter-icon {
  padding: 0 18rpx;
  margin: 0;
  font-size: 40rpx;
  color: #007aff;
  border-left: 1rpx solid #f3f3f3;
}

.round {
  border-radius: 2500px;
}

.cu-bar .search-form+.action {
  margin-right: 30rpx;
}

.cu-bar .action {
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 100%;
  height: 100%;
}

.search-container .action .cu-btn {
  padding: 0 24rpx;
}

.bg-gradual-green {
  color: #fff;
  background-image: linear-gradient(45deg, #39b54a, #8dc63f);
}

.bg-gradual-blue {
  color: #fff;
  background-image: linear-gradient(45deg, #0c62d3, #2a73d3);
}

.cu-btn {
  position: relative;
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 64rpx;
  padding: 0 30rpx;
  margin-right: initial;
  margin-left: initial;
  overflow: visible;
  font-size: 28rpx;
  line-height: 1;
  text-align: center;
  text-decoration: none;
  border: 0;
  transform: translate(0, 0);
}

.tabs {
  display: flex;
  justify-content: space-between;
  padding: 0 50rpx;
  margin-top: 15rpx;

  .item {
    position: relative;
    padding: 15rpx 0;
    font-size: 30rpx;
    color: #fff;
    text-align: center;
    opacity: 0.5;
    transition: all 0.3s;

    &.on {
      opacity: 1;

      &::after {
        position: absolute;
        bottom: -8rpx;
        left: 50%;
        width: 12rpx;
        height: 12rpx;
        content: '';
        background: #f1f1f1;
        border-radius: 50%;
        transform: translate(-50%);
      }
    }
  }
}

// :deep(.wd-navbar) {
// 	background: inherit;
// }

.cu-dialog {
  font-size: 28rpx;
}

.cu-dialog>.cu-bar:first-child .action {
  margin-right: 20rpx;
}

.filter_container {
  padding: 32rpx;
  padding-bottom: 64rpx;
  text-align: left;
  background-color: #fff;

  .block {
    ~.block {
      margin-top: 32rpx;
    }

    .label {
      margin-bottom: 20rpx;
      font-weight: bold;
    }
  }

  .row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;

    .date-picker {
      flex: 1;
      padding: 16rpx;
      text-align: center;
      background-color: #f7f7f7;
      border-radius: 8rpx;
    }

    .select-box {
      flex: 1;
      padding: 16rpx;
      background-color: #f7f7f7;
      border-radius: 8rpx;

      :deep(.select-row) {
        padding: 0;
        background: none;
      }
    }

    input {
      flex: 1;
      height: 33rpx;
      padding: 16rpx 12rpx;
      font-size: 26rpx !important;
      background-color: #f7f7f7;
      border: 1rpx solid #f7f7f7;
      border-radius: 8rpx;

      .input-placeholder {
        color: #8a929f;
      }
    }

    .btn {
      flex: 1;
      padding: 16rpx;
      color: #999;
      text-align: center;
      background-color: #f7f7f7;
      border: 1rpx solid #dedede;
      border-radius: 8rpx;

      ~.btn {
        margin-left: 24rpx;
      }

      &.primary {
        color: #fff;
        background-color: #007aff;
        border-color: #007aff;
      }
    }
  }
}

:deep(.wd-navbar__left--hover) {
  background: none;
}

.s-date {
  .wd-picker__cell {
    padding-right: 0 !important;
    padding-left: 0 !important;
  }
}
</style>
